<?php
namespace Model;

class WechatService
{
    public $AppID = 'wxafb5cf0cd17eaef9';
    public $AppSecret = 'ac8a47188924efa4ff1f09c0b2cfd60d';

    private function curlRequest($url,$method = 'GET',$data = array())
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if($method == 'POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
        }
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
    
    private function getServiceToken()
    {
        $token = M2('wexin_token')->where(array('id'=>1))->getField('token');
        return $token;
    }
    
    private function getSubscriptionToken()
    {
        $token = M2('wexin_token')->where(array('id'=>3))->getField('token');
        return $token;
    }
    
    public function getRecord($starTime,$endTime)
    {
        $time = time();

        $page = 1;
        while(($result = $this->getServiceRecord($starTime,$endTime,$page)) == true)
        {
            foreach ($result as $key => $value)
            {
                $recordRow = M('wechat_customservice_record')->where(array('openID'=>$value['openid'],'operCode'=>$value['opercode'],'sendTime'=>$value['time']))->find();
                if(empty($recordRow) == true)
                {
                    $data = array();
                    $data['channel']       = 1;
                    $data['openID']        = $value['openid'];
                    $data['operCode']      = $value['opercode'];
                    $data['content']       = trim($value['text']);
                    $data['worker']        = trim($value['worker']);
                    $data['sendTime']      = $value['time'];
                    $data['entryTime']     = $time;
                    	
                    M('wechat_customservice_record')->add($data);
                }
            }
            $page++;
        }

        $page = 1;
        while(($result = $this->getSubscriptionRecord($starTime,$endTime,$page)) == true)
        {
            foreach ($result as $key => $value)
            {
                $recordRow = M('wechat_customservice_record')->where(array('openID'=>$value['openid'],'operCode'=>$value['opercode'],'sendTime'=>$value['time']))->find();
                if(empty($recordRow) == true)
                {
                    $data = array();
                    $data['channel']       = 2;
                    $data['openID']        = $value['openid'];
                    $data['operCode']      = $value['opercode'];
                    $data['content']       = trim($value['text']);
                    $data['worker']        = trim($value['worker']);
                    $data['sendTime']      = $value['time'];
                    $data['entryTime']     = $time;
                     
                    M('wechat_customservice_record')->add($data);
                }
            }
            $page++;
        }
        
        $this->recordAnalysis($time);
    }

    private function recordAnalysis($time)
    {
        $record = M('wechat_customservice_record')->where(array('entryTime'=>$time))->order('openID asc,sendTime ASC')->select();
        $customerOpenID = array();
        foreach ($record as $key => $value)
        {
            $customerOpenID[$key] = $value['openID'];
            switch ($value['operCode'])
            {
                //会话接入
                case 1001:
                    $conversationRow = M('wechat_customservice_conversation')->where(array('channel'=>$value['channel'],'openID'=>$value['openID'],'status'=>array('neq',-1)))->find();
                    if(empty($conversationRow) == false)
                    {
                        $conversationDetail = array();
                        $conversationDetail['conversationID']      = $conversationRow['id'];
                        $conversationDetail['openID']              = $value['openID'];
                        $conversationDetail['worker']              = $value['worker'];
                        $conversationDetail['content']             = '会话接入';
                        $conversationDetail['time']                = $value['sendTime'];
                        $conversationDetail['mode']                = 1;
                         
                        M('wechat_customservice_conversation_detail')->add($conversationDetail);
                         
                        M('wechat_customservice_conversation')->where(array('id'=>$conversationRow['id']))->save(array('status'=>1,'worker'=>$value['worker'],'responseTime'=>$value['sendTime']));
                    }
                    break;
                    //会话关闭
                case 1004:
                    $conversationRow = M('wechat_customservice_conversation')->where(array('channel'=>$value['channel'],'openID'=>$value['openID'],'status'=>array('neq',-1)))->find();
                    if(empty($conversationRow) == false)
                    {
                        $conversationDetail = array();
                        $conversationDetail['conversationID']   = $conversationRow['id'];
                        $conversationDetail['openID']           = $value['openID'];
                        $conversationDetail['worker']           = $value['worker'];
                        $conversationDetail['content']          = '会话关闭';
                        $conversationDetail['time']             = $value['sendTime'];
                        $conversationDetail['mode']             = 2;
    
                        M('wechat_customservice_conversation_detail')->add($conversationDetail);
    
                        M('wechat_customservice_conversation')->where(array('id'=>$conversationRow['id']))->save(array('status'=>-1));
                    }
                    break;
                    //公众号信息
                case 2001:
                    $conversationRow = M('wechat_customservice_conversation')->where(array('channel'=>$value['channel'],'openID'=>$value['openID'],'status'=>array('neq',-1)))->find();
                    if(empty($conversationRow) == false)
                    {
                        $conversationDetail = array();
                        $conversationDetail['conversationID']   = $conversationRow['id'];
                        $conversationDetail['openID']           = $value['openID'];
                        $conversationDetail['worker']           = $value['worker'];
                        $conversationDetail['content']          = $value['content'];
                        $conversationDetail['time']             = $value['sendTime'];
                        $conversationDetail['mode']             = 3;
    
                        M('wechat_customservice_conversation_detail')->add($conversationDetail);
                        M('wechat_customservice_conversation')->where(array('id'=>$conversationRow['id']))->save(array('askCount'=>array('exp','askCount+1')));
                    }
                    else
                    {
                        $conversation = array();
                        $conversation['channel']        = $value['channel'];
                        $conversation['class']          = 0;
                        $conversation['openID']         = $value['openID'];
                        $conversation['worker']         = $value['worker'];
                        $conversation['sendTime']       = $value['sendTime'];
                        $conversation['askCount']       = 1;
                        $conversation['answerCount']    = 0;
                        $conversation['responseTime']   = 0;
                        $conversation['status']         = 0;
                         
                        $conversationID = M('wechat_customservice_conversation')->add($conversation);
    
                        $conversationDetail = array();
                        $conversationDetail['conversationID']   = $conversationID;
                        $conversationDetail['openID']           = $value['openID'];
                        $conversationDetail['worker']           = $value['worker'];
                        $conversationDetail['content']          = $value['content'];
                        $conversationDetail['time']             = $value['sendTime'];
                        $conversationDetail['mode']             = 3;
    
                        M('wechat_customservice_conversation_detail')->add($conversationDetail);
                    }
                    break;
                    //客户信息
                case 2003:
                    $conversationRow = M('wechat_customservice_conversation')->where(array('channel'=>$value['channel'],'openID'=>$value['openID'],'status'=>array('neq',-1)))->find();
                    if(empty($conversationRow) == false)
                    {
                        $conversationDetail = array();
                        $conversationDetail['conversationID']   = $conversationRow['id'];
                        $conversationDetail['openID']           = $value['openID'];
                        $conversationDetail['worker']           = $value['worker'];
                        $conversationDetail['content']          = $value['content'];
                        $conversationDetail['time']             = $value['sendTime'];
                        $conversationDetail['mode']             = 3;
    
                        M('wechat_customservice_conversation_detail')->add($conversationDetail);
                        M('wechat_customservice_conversation')->where(array('id'=>$conversationRow['id']))->save(array('askCount'=>array('exp','askCount+1')));
                    }
                    else
                    {
                        $conversation = array();
                        $conversation['channel']        = $value['channel'];
                        $conversation['class']          = 0;
                        $conversation['openID']         = $value['openID'];
                        $conversation['worker']         = $value['worker'];
                        $conversation['sendTime']       = $value['sendTime'];
                        $conversation['askCount']       = 1;
                        $conversation['answerCount']    = 0;
                        $conversation['responseTime']   = 0;
                        $conversation['status']         = 0;
                         
                        $conversationID = M('wechat_customservice_conversation')->add($conversation);
    
                        $conversationDetail = array();
                        $conversationDetail['conversationID']   = $conversationID;
                        $conversationDetail['openID']           = $value['openID'];
                        $conversationDetail['worker']           = $value['worker'];
                        $conversationDetail['content']          = $value['content'];
                        $conversationDetail['time']             = $value['sendTime'];
                        $conversationDetail['mode']             = 3;
    
                        M('wechat_customservice_conversation_detail')->add($conversationDetail);
                    }
                    break;
                    //客服回复
                case 2002:
                    $conversationRow = M('wechat_customservice_conversation')->where(array('channel'=>$value['channel'],'openID'=>$value['openID'],'status'=>array('neq',-1)))->find();
                    if(empty($conversationRow) == false)
                    {
                        if($conversationRow['status'] == 0)
                        {
                            $conversationDetail = array();
                            $conversationDetail['conversationID']   = $conversationRow['id'];
                            $conversationDetail['openID']           = $value['openID'];
                            $conversationDetail['worker']           = $value['worker'];
                            $conversationDetail['content']          = '会话接入';
                            $conversationDetail['time']             = $value['sendTime'];
                            $conversationDetail['mode']             = 1;
                             
                            M('wechat_customservice_conversation_detail')->add($conversationDetail);
                             
                            M('wechat_customservice_conversation')->where(array('id'=>$conversationRow['id']))->save(array('status'=>1,'worker'=>$value['worker'],'responseTime'=>$value['sendTime']));
                        }
                        
                        $conversationDetail = array();
                        $conversationDetail['conversationID']   = $conversationRow['id'];
                        $conversationDetail['openID']           = $value['openID'];
                        $conversationDetail['worker']           = $value['worker'];
                        $conversationDetail['content']          = $value['content'];
                        $conversationDetail['time']             = $value['sendTime'];
                        $conversationDetail['mode']             = 4;
    
                        M('wechat_customservice_conversation_detail')->add($conversationDetail);
    
                        M('wechat_customservice_conversation')->where(array('id'=>$conversationRow['id']))->save(array('worker'=>$value['worker'],'answerCount'=>array('exp','answerCount+1')));
                    }
            }
        }
         
        //加入会员库
        $customerOpenID = array_values(array_unique($customerOpenID));
        $libraryOpenID = M('wechat_customservice_customer')->where(array('channel'=>1))->getField('openID',true);
        $libraryOpenID = $libraryOpenID == false?array():$libraryOpenID;
        $commonOpenID = array_intersect($customerOpenID, $libraryOpenID);
        $diffOpenID = array_diff($customerOpenID, $commonOpenID);
    
        foreach($diffOpenID as $key => $value)
        {
            $channel = M('wechat_customservice_record')->where(array('openID'=>$value))->getField('channel');
            $customer = $this->getCustomerInfo($value,$channel);
    
            $customerInfo = array();
            $customerInfo['channel']    = $channel;
            $customerInfo['openID']     = $customer['openid'];
            $customerInfo['nickName']   = $customer['nickname'];
            $customerInfo['realName']   = '';
            $customerInfo['email']      = '';
            $customerInfo['mobile']     = '';
            $customerInfo['sex']        = $customer['sex'];
            $customerInfo['country']    = $customer['country'];
            $customerInfo['province']   = $customer['province'];
            $customerInfo['city']       = $customer['city'];
            $customerInfo['time']       = time();
    
            M('wechat_customservice_customer')->add($customerInfo);
        }
    }    
    
    public function getServiceRecord($starTime,$endTime,$page)
    {
        $data = array();
        $data['starttime']  = $starTime;
        $data['endtime']    = $endTime;
        $data['pageindex']  = $page;
        $data['pagesize']   = 50;
        $data = json_encode($data);

        $token = $this->getServiceToken();
        $url = "https://api.weixin.qq.com/customservice/msgrecord/getrecord?access_token=".$token;
        
        $result = $this->curlRequest($url,'POST',$data);
        $result = json_decode($result, true);
        return $result['recordlist'];
    }
    
    public function getSubscriptionRecord($starTime,$endTime,$page)
    {
        $data = array();
        $data['starttime']  = $starTime;
        $data['endtime']    = $endTime;
        $data['pageindex']  = $page;
        $data['pagesize']   = 50;
        $data = json_encode($data);
    
        $token = $this->getSubscriptionToken();
        $url = "https://api.weixin.qq.com/customservice/msgrecord/getrecord?access_token=".$token;
    
        $result = $this->curlRequest($url,'POST',$data);
        $result = json_decode($result, true);
        return $result['recordlist'];
    }

    public function getCustomerInfo($openID,$channel)
    {
        switch ($channel)
        {
            case 1:
                $token = $this->getServiceToken();
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$openID."&lang=zh_CN";
                $result = $this->curlRequest($url);
                $result = json_decode($result, true);
                return $result;
                break;
            case 2:
                $token = $this->getSubscriptionToken();
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$openID."&lang=zh_CN";
                $result = $this->curlRequest($url);
                $result = json_decode($result, true);
                return $result;
                break;
        }

    }
    
    public function getWorder()
    {
        $kf_list = array();
        
        $token = $this->getServiceToken();
        $url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=".$token;
        $result = $this->curlRequest($url);
        $result = json_decode($result, true);
        foreach ($result['kf_list'] as $key => $value)
        {
            $result['kf_list'][$key]['channel'] = 1;
            $kf_list[] = $result['kf_list'][$key];
        }
        
        $token = $this->getSubscriptionToken();
        $url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=".$token;
        $result = $this->curlRequest($url);
        $result = json_decode($result, true);

        foreach ($result['kf_list'] as $key => $value)
        {
            $result['kf_list'][$key]['channel'] = 2;
            $kf_list[] = $result['kf_list'][$key];
        }

        foreach ($kf_list as $key => $value)
        {
            $workerGroupRow = M('wechat_customservice_worker_group')->where(array('account'=>strstr($value['kf_account'],'@',true)))->find();
            if(empty($workerGroupRow) == true)
            {
                $worker = array();
                $worker['account']      = strstr($value['kf_account'],'@',true);
                $worker['nikeName']     = $value['kf_nick'];
                $worker['status']       = 1;
                $worker['time']         = time();
                 
                $groupID = M('wechat_customservice_worker_group')->add($worker);
            }
            else
            {
                $groupID = $workerGroupRow['id'];
            }
             
            $workerRow = M('wechat_customservice_worker')->where(array('channel'=>1,'account'=>$value['kf_account']))->find();
            if(empty($workerRow) == true)
            {
                $worker = array();
                $worker['groupID']      = $groupID;
                $worker['channel']      = $value['channel'];
                $worker['workID']       = $value['kf_id'];
                $worker['account']      = $value['kf_account'];
                $worker['nikeName']     = $value['kf_nick'];
                $worker['time']         = time();
            
                M('wechat_customservice_worker')->add($worker);
            }
        }
    }
    
    public function getOnlineWorder()
    {
        $kf_online_list = array();
        
        $token = $this->getServiceToken();
        $url = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=".$token;
        $result = $this->curlRequest($url);
        $result = json_decode($result, true);
        foreach ($result['kf_online_list'] as $key => $value)
        {
            $result['kf_online_list'][$key]['channel'] = 1;
            $kf_online_list[] = $result['kf_online_list'][$key];
        }
        
        $token = $this->getSubscriptionToken();
        $url = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=".$token;
        $result = $this->curlRequest($url);
        $result = json_decode($result, true);
        foreach ($result['kf_online_list'] as $key => $value)
        {
            $result['kf_online_list'][$key]['channel'] = 2;
            $kf_online_list[] = $result['kf_online_list'][$key];
        }
        
        return count($kf_online_list);
    }
}




